package com.atguigu.IO;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TcpTranslateServer extends TcpEchoServer{
    private Map<String,String> dict=new HashMap<>();
    private ServerSocket serverSocket=null;
    public TcpTranslateServer(int port) throws IOException {
        super(port);
        dict.put("cat","小猫");
        dict.put("dog","小狗");
        dict.put("kunkun","鸡哥");
        dict.put("duck","鸭");
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer server=new TcpEchoServer(9090);
        server.start();
    }

    public void start() throws IOException {
        System.out.println("服务器启动");
        ExecutorService service= Executors.newCachedThreadPool();
        while(true){
            Socket socket = serverSocket.accept();
            service.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        processClient(socket);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }

    private void processClient(Socket socket) throws IOException {
        System.out.printf("[%s: %d] 客户端上线",socket.getInetAddress().toString(),socket.getPort());
        //接下来处理客户端的请求
        try(InputStream inputStream= socket.getInputStream();
            OutputStream outputStream=socket.getOutputStream()) {
            while(true){
                //1.读取请求并解析
                Scanner scanner=new Scanner(System.in);
                if(!scanner.hasNext()){
                    //连接断开
                    System.out.println("客户端下线"+socket.getInetAddress().toString()+socket.getPort());
                    break;
                }
                String request=scanner.next();
                //2.根据请求计算相应
                String response=process(request);
                //3.把响应写回客户端
                PrintWriter printWriter=new PrintWriter(outputStream);
                printWriter.println(response);
                //刷新缓冲区
                printWriter.flush();
                System.out.printf("[%s %d] req:%s resp: %s\n",socket.getInetAddress().toString(),socket.getPort(),
                        request,response);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            socket.close();

        }
    }

    public String process(String request) {
        return dict.getOrDefault(request,"词在词典中未找到");
    }
}
